import React, { Component } from 'react';
import './category.css';
import { Card, Button, Table, Modal, Form, Input, message, Popconfirm } from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import store from '../../store';
import { reqGetCategory, reqAddCategory, reqDelCategory, reqUpdataCategory } from '../../api';


class Category extends Component {
    constructor(props) {
        super();
        this.state = {
            isLoading: store.getState().isLoading,
            visibleAdd: false, //控制添加页面显示隐藏
            visibleAdd2: false, //控制修改页面显示隐藏
            changIndex: 0, //修改的数据下标
            card: {
                tit: '品类管理',
                dataSource: [],
                columns: [
                    {
                        title: '序号',
                        dataIndex: 'index',
                        key: 'index',
                    },
                    {
                        title: '编号',
                        dataIndex: 'id',
                        key: 'id',
                    },
                    {
                        title: '类型',
                        dataIndex: 'typename',
                        key: 'typename',
                    },
                    {
                        title: '操作',
                        dataIndex: '',
                        key: 'action',
                        render: (text, record) => {
                            return (
                                <>
                                    <Button onClick={() => { this.showChangeModal(record.id, record.index) }}>修改</Button>
                                    <Popconfirm
                                        title="您真的要删除吗"
                                        onConfirm={() => { this.delCategory(record.id, record.index) }}
                                        onCancel={this.cancel}
                                        okText="是的"
                                        cancelText="取消"
                                        size='large'
                                    >
                                        <Button>删除</Button>
                                    </Popconfirm>
                                </>
                            )
                        }
                    }
                ],
            },
            // 添加类别的临时变量
            addCategory: {
                id: '',
                typename: '',
            },
            // 修改类别的临时变量
            changeCategory: {
                id: '',
                typename: '',
            }
        }
    }
    // 控制添加Modal的显示
    showModal = () => {
        this.setState({
            visibleAdd: true,
        });
    };
    hideModal = () => {
        this.setState({
            visibleAdd: false,
        });
    };
    // 控制修改Modal的显示
    showChangeModal = (id, index) => {
        this.setState({
            changIndex: index - 1,
            visibleAdd2: true,
            changeCategory: {
                'id': this.state.card.dataSource[index - 1].id,
                'typename': this.state.card.dataSource[index - 1].typename
            }
        });
    };
    hideChangeModal = () => {
        this.setState({
            visibleAdd2: false,
        });
    };
    // 点击删除后删除类别
    delCategory = (id, index) => {
        // 后端删除
        reqDelCategory(id).then(() => {
            message.success('删除成功');
            //前端删除
            let cover = this.state.card.dataSource
            cover.splice(index - 1, 1);
            console.log(cover);
            this.setState({
                card: {
                    ...this.state.card,
                    dataSource: cover
                }
            })
            window.location.reload();
        }).catch(() => {
            message.error('删除失败');
        })
    }
    addData = () => {
        this.showModal();
    }

    //确认修改类别
    onOKChangge = async () => {
        //后端修改 
        let id = this.state.card.dataSource[this.state.changIndex].id;
        let data = this.state.changeCategory;
        try {
            console.log('id', id);
            console.log('data', data);
            let res = await reqUpdataCategory(id, data);
            if (res.data) {
                message.success('修改成功');
                //前端修改
                let cover = this.state.card.dataSource;
                cover.splice(this.state.changIndex, 1, this.state.changeCategory);
                this.setState({
                    card: {
                        ...this.state.card,
                        dataSource: cover
                    }
                })
                setTimeout(() => {
                    this.hideChangeModal();
                    window.location.reload();
                }, 300);
            } else {
                message.error('修改失败');
            }
        } catch {
            message.error('修改失败');
        }
    }


    // 确认添加类别
    onFinish = (ev) => {
        // 点击保存后
        reqAddCategory(this.state.addCategory).then(res => {
            if (res.data) {
                message.success('添加成功');
                // 清空inp
                let idInp = document.getElementsByName('id');
                let typeNameInp = document.getElementsByName('typename');
                idInp[0].value = '';
                typeNameInp[0].value = '';
                this.setState({
                    addCategory: {
                        id: '',
                        typename: '',
                    }
                })
                // 更新列表
                let cover = this.state.card.dataSource
                cover.push(res.data);
                this.setState({
                    card: {
                        ...this.state.card,
                        dataSource: cover
                    }
                });
                // 关闭Model
                setTimeout(() => {
                    this.hideModal();
                    window.location.reload();
                }, 300);
            }

        }).catch(() => {
            message.error('添加失败')
        })
    };

    //添加框的数据的双向绑定
    doubleBind = (ev) => {
        this.setState({
            addCategory: {
                ...this.state.addCategory,
                [ev.target.name]: ev.target.value
            }
        })
    }
    doubleBind_change = (ev) => {
        this.setState({
            changeCategory: {
                ...this.state.changeCategory,
                [ev.target.name]: ev.target.value
            }
        })
    }
    async componentDidMount() {
        store.subscribe(() => {
            this.setState({
                isLoading: store.getState().isLoading
            })
        })
        store.dispatch({ type: 'toTrue' });
        let res = await reqGetCategory();
        res.data.forEach((item, index) => {
            item.key = item.id;
            item.index = index + 1;
        });

        let cover = this.state.card;
        cover.dataSource = res.data;
        this.setState({
            card: cover
        },
            () => {
                store.dispatch({ type: 'toFalse' })
            }
        )
    }
    render() {
        //添加表单的位置配置
        const layout = {
            labelCol: {
                span: 5,
            },
            wrapperCol: {
                span: 16,
            },
        };
        const validateMessages = {
            required: '${label}不能为空 '
        };
        // Card的标题
        let extra = (
            <Button type="primary" shape="round" icon={<PlusOutlined />} size='small' onClick={this.addData}>
                添加
            </Button>
        )
        const { dataSource, columns } = { ...this.state.card };
        return (
            <>
                <Card title={this.state.card.tit} extra={extra} style={{ width: '100%' }}>
                    <Table
                        loading={this.state.isLoading}
                        dataSource={dataSource}
                        columns={columns}
                        className='ant-table'
                        style={{ textAlign: "center" }}
                    />
                </Card>
                <Modal
                    title="添加类别"
                    visible={this.state.visibleAdd}
                    onOk={this.onFinish}
                    onCancel={this.hideModal}
                    okText="保存"
                    cancelText="取消"
                >

                    <Form {...layout} name="nest-messages" onFinish={this.onFinish} validateMessages={validateMessages}>
                        <Form.Item
                            label="编号"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            {console.log(this.state.addCategory.id)}
                            <Input name='id' value={this.state.addCategory.id} onChange={this.doubleBind} autoComplete="off" />
                        </Form.Item>
                        <Form.Item
                            label="类别"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            {console.log(this.state.addCategory.typename)}
                            <Input name='typename' value={this.state.addCategory.typename} onChange={this.doubleBind} autoComplete="off" />
                        </Form.Item>

                    </Form>
                </Modal>
                <Modal title="修改类别"
                    visible={this.state.visibleAdd2}
                    onOk={this.onOKChangge}
                    onCancel={this.hideChangeModal}
                    okText="修改"
                    cancelText="取消"
                >
                    <div style={{ width: '100%', margin: '10px 60px' }}>编号：<Input style={{ width: '60%' }} name='id' autoComplete="off" value={this.state.changeCategory.id} onChange={this.doubleBind_change}></Input></div>
                    <div style={{ width: '100%', margin: '10px 60px' }}>类别：<Input style={{ width: '60%' }} name='typename' autoComplete="off" value={this.state.changeCategory.typename} onChange={this.doubleBind_change}></Input></div>
                </Modal>
            </>
        );
    }
}

export default Category;